package com.ujiuye.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujiuye.pojo.Permission;
import com.ujiuye.pojo.Role;
import com.ujiuye.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Reference
    private IUserService userService;
    @Reference
    private IRoleService roleService;
    @Reference
    private IPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
          //先通过用户名查询用户
        User user = userService.getUserByName(name);
        //没有查询的到报一个异常
        if (user==null){
            throw new UsernameNotFoundException("用户名不正确");
        }
         //自己写sql语句查询该用户有什么角色
        List<Role> roleList = roleService.getRoleById(user.getId());
        //自己写sql语句查询该用户有什么权限
        List<Permission> permissionList = permissionService.getPermissionById(user.getId());
        //创建一个GrantedAuthority集合
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
         //将查询到的所有的角色放入刚刚创建的集合中让springsecurity对其进行管理
        for (Role role : roleList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
        }
        //将查询到的所有的权限放入刚刚创建的集合中让springsecurity对其进行管理
        for (Permission permission : permissionList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),grantedAuthorityList);
    }
}
